package py.una.pol.tesis.ii.emergenciasmovil.app.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import py.una.pol.tesis.ii.emergenciasmovil.app.R;
import py.una.pol.tesis.ii.emergenciasmovil.app.dto.Historial;

/**
 * Created by leandro on 9/11/2014.
 */
public class HistorialListAdapter extends BaseAdapter {
    private static final String TAG = "HistorialListAdapter";
    protected Activity activity;
    private Context context;
    ArrayList<Historial> notificacionArray = new ArrayList<Historial>();;
    List<Historial> notificacionList = new ArrayList<Historial>();
    private int pos;
    private RequestQueue requestQueue;
    private JsonObjectRequest jsArrayRequest;

    public HistorialListAdapter(Activity activity) {
        this.activity = activity;
        requestQueue = Volley.newRequestQueue(activity);
        jsArrayRequest = new JsonObjectRequest(Request.Method.GET,
                activity.getString(R.string.url_base) + activity.getString(R.string.get_historial_paciente),
                "",
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        notificacionList = parseJson(response);
                        notificacionArray.addAll(notificacionList);
                        notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "Error Respuesta en JSON: " + error.getMessage());

                    }
                }

        );

        requestQueue.add(jsArrayRequest);
    }

    @Override
    public int getCount() {
        return notificacionList.size();
    }

    @Override
    public Object getItem(int i) {
        return notificacionList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup parent) {
        if (view == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            view = mInflater.inflate(R.layout.item_list_historial, null);
        }
        this.pos = i;
        TextView tituloDiag = (TextView) view.findViewById(R.id.tituloDiag);
        tituloDiag.setText(notificacionList.get(i).getDiagnostico());

        TextView doctor = (TextView) view.findViewById(R.id.doctor);
        doctor.setText(notificacionList.get(i).getDoctor());

        TextView regla = (TextView) view.findViewById(R.id.regla);
        regla.setText(notificacionList.get(i).getRegla());

        TextView medicion = (TextView) view.findViewById(R.id.medicion);
        medicion.setText(notificacionList.get(i).getMedicion());

        TextView fecha = (TextView) view.findViewById(R.id.fechaHist);
        fecha.setText(notificacionList.get(i).getFecha());

        ImageButton sharingButton = (ImageButton) view.findViewById(R.id.compartir);
        sharingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareIt();
            }
        });

        return view;
    }

    private void shareIt() {
        Historial notificacion = notificacionList.get(this.pos);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide
        // what to do with it.

        share.putExtra(Intent.EXTRA_SUBJECT, "Unasur Notifica: " + notificacion.getMedicion());
        share.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.unasur.android");

        activity.startActivity(Intent.createChooser(share, "Compartir Notificación!"));
    }

    public void filtrar(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        notificacionList.clear();
        if (charText.length() == 0) {
            notificacionList.addAll(notificacionArray);
        } else {
            for (Historial noti : notificacionArray) {
                if (noti.getDoctor().toLowerCase(Locale.getDefault()).contains(charText)) {
                    notificacionList.add(noti);
                }
            }
        }
        notifyDataSetChanged();
    }

    public List<Historial> parseJson(JSONObject jsonObject) {
        // Variables locales
        List<Historial> historiales = new ArrayList();

        /*final Gson gson = new Gson();
        final Type tipoListaHistorial = new TypeToken<List<Historial>>(){}.getType();
        historiales = gson.fromJson(jsonObject.toString(), tipoListaHistorial);*/

        JSONArray jsonArray = null;

        try {
            // Obtener el array del objeto
            jsonArray = jsonObject.getJSONArray("items");

            for (int i = 0; i < jsonArray.length(); i++) {

                try {
                    JSONObject objeto = jsonArray.getJSONObject(i);
                    Historial historial = new Historial(
                            objeto.getInt("idHistorial"),
                            objeto.getString("doctor"),
                            objeto.getString("fecha"),
                            objeto.getString("regla"),
                            objeto.getString("medicion"),
                            objeto.getString("diagnostico"));


                    historiales.add(historial);

                } catch (JSONException e) {
                    Log.e(TAG, "Error de parsing: " + e.getMessage());
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }


        return historiales;
    }

}
